<template>
  <Header title="计算器" />
  <div :class="['container', name]" ref="dom">
    <!-- <img class="head" :src="getImageUrl(`${name}_head.jpg`)" alt=""> -->
    <p class="slogan">{{ name =='footballVerify'? '足球':'篮球' }}</p>
    <div class="time">
      {{ todaystr.ymd }}
      <span>{{ todaystr.week }}</span>
    </div>
    <div class="main">
      <div class="item" v-for="(value, index) in matches" :key="index">
        <div class="top">
          <p>
            <span>{{ value.week }}{{ value.weekno }}</span>
            <span>{{ value.cup }}</span>
            <span>{{ MyUtils.dateFormat(value.jtime * 1000, 'MM-DD hh:mm') }}</span>
          </p>
          <div :class="name">
            <img v-if="value.h_icon" :src="picPath + value.h_icon" alt="">
            <img v-else src="@/assets/image/shopColorTools/match_home_default.png" alt="">
            <em class='post' v-if="value.home_position">{{ `[${value.home_position}]` }}</em>
            <span>{{ value.home }}</span>
            <span>vs</span>
            <span>{{ value.guest }}</span>
            <em class="post" v-if="value.guest_position">{{ `[${value.guest_position}]` }}</em>
            <img v-if="value.g_icon" :src="picPath + value.g_icon" alt="">
            <img v-else src="@/assets/image/shopColorTools/match_guest_default.png" alt="">
          </div>
        </div>
        <div class="bottom">
          <template v-for="(item1, index1) in ['had', 'hhad', 'crs', 'ttg', 'hafu', 'mnl', 'hdc', 'hilo', 'wnm']">
            <template v-for="(item2, index2) in value[item1]">
              <span v-if="value[item1]" :key="index2 + index1">
                <em class="em_red">{{ item2.result }}</em> {{ item2.odds }}
              </span>
            </template>
          </template>
        </div>
      </div>
      <div class="point">
        <div>
          <p class="inline">
            串关方式:
            <em v-for="(item, index) in cgArr" :key="index">{{ item }}</em>
            <!-- <template v-if="name === 'footballVerify'">
                <em v-for="(item, index) in modelInfos" :key="index">{{item.text}}</em>
              </template>
              <template v-else>
                <em v-for="(item, index) in Index" :key="index">{{item.replace('*', '串')}}</em>
              </template> -->
          </p>
          <span class="inline">投注金额:<em>{{ price }}元</em></span>
          <span class="inline">预计奖金:<em>{{ Number(totalInfo.min).toFixed(2) + '~' +
              Number(totalInfo.max).toFixed(2) }}元</em></span>
          <span class="inline">倍数:<em>{{ route.query.multiNum }}</em></span>
        </div>
        <div>{{ viewPoint }}</div>
      </div>
    </div>
    <!-- <img class="foot" :src="getImageUrl(`${name}_foot.jpg`)" alt=""> -->
  </div>
  <div class="placeholder van-safe-area-bottom"></div>
  <div class="fixedBottomBtns van-safe-area-bottom">
    <van-button color="linear-gradient(40deg, #f12a73, #fd5049)" block @click="generate()" v-if="imageUrl">
      查看海报
    </van-button>
    <van-button color="linear-gradient(40deg, #f12a73, #fd5049)" icon="down" block @click="generate()" v-else>
      生成海报
    </van-button>
  </div>
  <van-overlay :show="showImg" @click="showImg = false" z-index="2">
    <img v-if="imageUrl" :src="imageUrl" />
  </van-overlay>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useCalcStore } from "@/stores"
import MyUtils from "@/utils/calc"
import html2canvas from "html2canvas"
// import { getImageUrl } from "@/utils/helper"

const dom = ref();
const imageUrl = ref('')
const showImg = ref(false)
const router = useRouter()
const route = useRoute()
const calc = useCalcStore() // 竞猜store
const { raceColor, viewPoint } = storeToRefs(calc)
const picPath = "http://static.mojing310.com/";

// 今日时间戳
const todaystr = computed(() => {
  const _t = new Date()
  return {
    ymd: MyUtils.dateFormat(_t.getTime(), 'YYYY-MM-DD'),
    week: MyUtils.getWeek(_t, '星期')
  }
})
const cgArr = computed(() => {
  const ary = route.query.cg.replace(/_/g, '串').split(',')
  return ary.map(v => v.replace('1串1', '单关'))
})
// 传入的类型 basketballVerify篮球 footballVerify足球
const name = ref(route.query.name)
// 投注金额|奖金
const price = ref(0)
const rangePrice = ref(0)
if (name.value === 'footballVerify') {
  price.value = route.query.allPrice
  rangePrice.value = route.query.maxBonus
} else {
  price.value = route.query.allPrice
  rangePrice.value = route.query.maxBonus
}
// 按照 开赛时间+周号 进行升序排序
const json = JSON.parse(JSON.stringify(raceColor.value))
const matches = Object.values(json).map((itm) => {
  const date = new Date(itm.jtime * 1000)
  // 提取年、月、日部分
  const year = date.getFullYear();
  const month = date.getMonth(); // 注意：getMonth()返回的月份是从0开始的（0-11）
  const day = date.getDate();
  // 创建一个当天零点的时间戳
  itm.wtime = new Date(year, month, day).getTime();
  return itm
}).sort((a, b) => {
  if (a.wtime === b.wtime) {
    return Number(a.weekno) - Number(b.weekno);
  } else {
    return a.wtime - b.wtime;
  }
})

async function generate(){
  showLoadingToast({ message: '海报生成中...', forbidClick: true, duration: 0 });
  if (!imageUrl.value){
    const canvas = await html2canvas(dom.value, { scale: 1 })
    if (canvas){
      imageUrl.value = canvas.toDataURL('image/png')
      showImg.value = true
      showNotify({ type: 'primary', message: '海报已生成,请长按图片保存!' });
    }
  }else{
    showImg.value = true
  }
  closeToast();
}

const totalInfo = reactive({ min: 0, max: 0 })
onBeforeMount(() => {
  const optData = JSON.parse(sessionStorage.getItem('optData'));
  const possibleComb = JSON.parse(sessionStorage.getItem('possibleComb'));
  // 根据所有的串关组合，计算出每种组合中的金额
  const moneys = optData.zuhe.map((itm) => {
    const _key = itm.reduce((pre, cur) => pre * cur[2], 1) * 2;
    const _strs = itm.map(item => `${item[6]}@${item[5]}@${item[3]}`);
    return { 'key': _key, 'lst': _strs };
  })
  // 取出倍数
  const { multiNum } = route.query;
  // 计算最小奖金[从所有的组合中找到金额最小的那个]
  const minMoneys = moneys.map((itm) => itm.key)
  totalInfo.min = Number(Math.min.apply(null, minMoneys).toFixed(2)) * multiNum;
  // 计算最大奖金[按照possibleComb数组对组合分组，并从中取出金额最大的]
  const maxMoneyArr = [];
  for (let pos of possibleComb) {
    let maxMoney = 0
    // 匹配上的累加金额
    for (let comp of moneys) {
      if (comp.lst.every(element => pos.includes(element))) {
        maxMoney += comp.key;
      }
    }
    // 记录每种可能性的总奖金
    maxMoneyArr.push(maxMoney);
  }
  // 从 maxMoneyArr 中取出最大值
  totalInfo.max = Number(Math.max.apply(null, maxMoneyArr).toFixed(2)) * multiNum;
})
</script>

<style lang="less" scoped>
// 所有的rem单位都得 x*50
.container {
  background-color: #ff3f00;
  padding: 10px 0;
  &.basketballVerify {
    background-color: #fb9e01;
  }
  .head,
  .foot {
    width: 100%;
    display: block;
  }
  .slogan{
    color: #fff;
    font-size: 24px;
    text-align: center;
  }
  .shop_name {
    position: absolute;
    left: 0;
    top: 65px;
    width: 100%;
    text-align: center;
    color: #fff;
    letter-spacing: 2.5px;
    font-size: 22px;
  }

  .time {
    width: 100%;
    top: 100px;
    color: #ffffb0;
    text-align: center;
    font-size: 12px;
    // position: absolute;
    // left: 0;
    // background-color: #ff3f00;

    span {
      margin-left: 2.5px;
    }
  }

  .main {
    padding: 7.5px;

    .item {
      width: 100%;
      border-radius: 10px;
      overflow: hidden;
      margin-bottom: 10px;

      .top {
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        align-items: center;
        height: 60px;
        width: 100%;
        background-color: #fff;

        >p {
          color: #afafaf;
          font-size: 11px;
          text-align: center;

          span {
            margin: 0 2.5px;
          }
        }

        >div {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          justify-content: center;
          color: #000;
          font-size: 16px;
          font-weight: bold;

          img {
            height: 37.5px;
          }

          span {
            color: #000;
            font-size: 16px;
            text-align: center;
            margin: 0 5px;

            &:nth-of-type(2) {
              font-size: 19px;
            }
          }

          .post {
            font-style: normal;
            font-size: 10px;
            color: #999;
          }

          &.basketballVerify {
            flex-direction: row-reverse;
          }
        }
      }

      .bottom {
        padding: 5px 0;
        font-size: 14px;
        font-weight: bold;
        text-align: center;
        background-color: #ffeac5;

        span {
          margin: 0 2.5px;
          display: inline-block;

          em {
            font-style: normal;
            color: #000;

            &.em_red {
              color: #ff0828;
            }
          }
        }
      }
    }

    .point {
      width: 100%;
      border: 2px solid #a02000;
      border-radius: 7.5px;
      background-color: #fff;
      padding: 10px;

      div {

        span,
        p {
          em {
            font-style: normal;
            margin: 0 1.5px;
            color: #000;
            font-weight: bold;
          }
        }

        .inline {
          display: inline-block;
          margin-right: 5px;
        }

        &:nth-of-type(1) {
          width: 100%;
          border-bottom: 0.5px solid #ccc;
          color: #ff0828;
          text-align: center;
          font-weight: 400;
          font-size: 13px;
          // display: flex;
          // justify-content: space-between;
          // align-items: center;
          padding: 2.5px;
        }

        &:nth-of-type(2) {
          width: 100%;
          color: #000;
          font-weight: 400;
          padding: 7.5px 4px;
        }
      }
    }
  }
}

.placeholder {
  height: 65px;
}

.fixedBottomBtns {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  height: 65px;
  padding: 10px 10px;
  border-top: 1px solid #ebedf0;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.van-overlay{
  display: flex;
  align-items: center;
  justify-content: center;
  --van-overlay-background: rgba(0, 0, 0, 0.9);
  img{
    user-select: none;
    max-width: 100%;
    max-height: 80%;
  }
}
</style>
